<?php
// +----------------------------------------------------------------------
// | WWW.0771MC.COM 广西南宁市铭成龙毅网络科技有限公司 出品
// +----------------------------------------------------------------------
// | Copyright (c) 2014 http://WWW.0771MC.COM All rights reserved.
// +----------------------------------------------------------------------
// | Author: 铭成龙毅 <service@0771mc.com> <http://www.0771MC.com>
// +----------------------------------------------------------------------
namespace User\Controller;

use Think\Controller;

class IndexController extends Controller
{

    public function _initialize()
    {
        if (C('cfg_user_auto') != 1) {
            $this->error('会员中心暂时关闭');
        }
    }

    public function index()
    {
        if (intval(get_cookie('uid'))) {
            $this->success('您已经成功登录！', U('User/Center/index'));
        } else {
            $refer = htmlspecialchars($_SERVER['HTTP_REFERER']);
            if (IS_POST) {
                $this->loginHandle();
            }
            $this->refer = $refer;
            $this->display();
        }
    }

    public function loginHandle()
    {
        $refer = I('post.refer');
        if (empty($refer) || strpos($refer, 'register') || strpos($refer, 'login') || strpos($refer, 'logout') || strpos($refer, 'activate') || strpos($refer, 'sendActivate')) {
            $refer = U('User/Center/index');
        }
        $mname = I('post.uname');
        $mpwd = I('post.upwd');
        $verify = I('post.verify', '', 'intval');
        $autoLogin = I('post.autoLogin');

        if (!check_verify($verify, 1)) {
            $this->error('验证码错误！');
        }

        if (!filter_var($mname, FILTER_VALIDATE_EMAIL)) {
            $this->error('账号为邮箱地址，格式不正确！');
        }

        if (strlen($mpwd) < 6 || strlen($mpwd) > 20) {
            $this->error('密码必须是6-20位的字符！');
        }

        //array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
        /*$validate = array(
            array('uname','require','邮箱必须填写！'), 
            //array('uname','email','帐号必须是邮箱格式！'),
            array('upwd','require','密码必须填写！'), 
            //array('upwd','6,20','密码必须6-20位字符！',3,'length'), 
        );*/

        $db = M('Member');


        //echo $db->_sql();
        /*if (!$db->validate($validate)->create()) {
            $this->error($db->getError());
        }*/

        $user = $db->where(array('email' => $mname))->find();

        //print_r($user);die;


        if (!$user || ($user['password'] != get_password($mpwd, $user['encrypt']))) {
            $this->error('账号或密码错误!');
        }
        if ($user['islock']) {
            $this->error('用户被锁定！', '', array('input' => ''));
        }
        if (!$user['status']) {
            $this->error('用户尚未激活！', '', array('input' => ''));
        }


        $data = array('id' => $user['id'],
            'logintime' => time(),
            'loginip' => get_client_ip(),
            'loginnum' => $user['loginnum'] + 1,

        );

        if ($db->save($data)) {
            set_cookie(array('name' => 'uid', 'value' => $user['id']));
            set_cookie(array('name' => 'face', 'value' => $user['face']));
            set_cookie(array('name' => 'email', 'value' => $user['email']));
            set_cookie(array('name' => 'nickname', 'value' => $user['nickname']));
            set_cookie(array('name' => 'logintime', 'value' => date('Y-m-d H:i:s', $user['logintime'])));
            set_cookie(array('name' => 'loginip', 'value' => $user['loginip']));
            set_cookie(array('name' => 'status', 'value' => $user['status'])); //激活状态
            set_cookie(array('name' => 'verifytime', 'value' => time())); //激活状态

            $this->success('登录成功！', $refer);
        } else {
            $this->error('登录失败！');
        }

    }

    public function regs()
    {

        if (intval(get_cookie('uid'))) {
            $this->success('您已经成功登录！', U('User/Center/index'));
        } else {
            $refer = $_SERVER['HTTP_REFERER'];
            if (IS_POST) {
                $this->regsHandle();
            }
            $this->refer = $refer;
            $this->display();
        }
    }

    public function regsHandle()
    {
        if (!IS_POST) {
            exit(0);
        }

        $password = I('upwd', '');
        $verify = I('verify', '', 'intval');

        if (!check_verify($verify, 1)) {
            $this->error('验证码错误！');
        }
        //M验证
        /*
        $rules = array(
            array('uname','require','电子邮箱必须填写！'),
            array('uname','email','邮箱格式不符合要求。'), 
            array('upwd','require','密码必须填写！'), 
            array('rupwd','require','确认密码必须填写！'), 
            array('upwd','rupwd','两次密码不一致',0,'confirm'),
            array('email','unique','邮箱已经存在！',0,'unique'), //使用这个是否存在，auto就不能自动完成
        );
        */


        $db = M('member');
        $User = D('Member');
        if (!$User->create()) {
            exit($User->getError());
        }

        if (strlen($password) < 4 || strlen($password) > 20) {
            $this->error('密码必须是4-20位的字符！', '', array('input' => 'password'));
        }

        $nickname = I('nickname', '', 'htmlspecialchars,trim');
        $notallowname = explode(',', C('cfg_member_notallow'));
        if (in_array($nickname, $notallowname)) {
            $this->error('此昵称系统禁用，请重新更换一个！');
        }

        $mGroup = M('membergroup')->Field('id')->find();
        if ($mGroup) {
            $data['groupid'] = $mGroup['id'];
        }
        $email = I('uname', '', 'htmlspecialchars,trim');
        $data['email'] = $email;
        $data['nickname'] = $nickname;

        $data['status'] = C('cfg_member_verifyemail') ? 0 : 1; //如果开启邮箱验证，则激活状态为0，否则为1即激活了。
        //代替自动完成
        $data['regtime'] = time();
        $passwordinfo = I('upwd', '', 'get_password');
        $data['password'] = $passwordinfo['password'];
        $data['encrypt'] = $passwordinfo['encrypt'];
        $regtime = date('Y年m月d日', time());
        $nextday = date('Y年m月d日 H:i', strtotime("+2 day"));
        $subject = "[{$cfg_webname}]请激活你的帐号，完成注册";


        if ($id = $db->add($data)) {

            $details['userid'] = $id;
            $details['birthday'] = time();

            if (M('memberdetail')->add($details)) {
                $msg = '注册会员成功<br/>';
            } else {
                $msg = '注册会员成功,但注册详细信息失败！';
            }


            $active['expire'] = strtotime("+2 day"); //二天后时间截,相当于time() + 2 * 24 * 60 * 60
            $active['code'] = get_randomstr(11);
            $active['userid'] = $id;
            $active['id'] = M('active')->add($active);


            $url = rtrim(C('cfg_weburl'), '/') . "/index.php?m=" . MODULE_NAME . "&c=Index&a=activate&va={$active['id']}&vc={$active['code']}";
            //$url = preg_replace("#http:\/\/#i", '', $url);
            //$url = 'http://'.preg_replace("#\/\/#i", '/', $url);

            $webname = C('cfg_webname');
            $weburl = C('cfg_weburl');
            $weburl2 = str_replace('http://www.', '', $weburl);
            $webqq = C('cfg_qq');
            $webmail = C('cfg_email');

            $subject = "[{$webname}]请激活你的帐号，完成注册";
            $message = <<<str
<p>您于 {$regtime} 注册{$webname}帐号 <a href="mailto:{$email}">{$email}</a> ，点击以下链接，即可激活该帐号：</p>
<p><a href="{$url}" target="_blank">{$url}</a></p>
<p>(如果您无法点击此链接，请将它复制到浏览器地址栏后访问)</p>
<p>为了保障您帐号的安全性，请在 48小时内完成激活，此链接将在您激活过一次后失效！</p>
<p>此邮件由系统发送，请勿直接回复。</p>
str;
            if (C('cfg_member_verifyemail')) {
                if (SendMail($email, $subject, $message) == true) {
                    $msg .= '验证邮件已发送，请尽快查收邮件，激活该帐号';
                } else {

                    $msg .= '验证邮件发送失败，请写管理员联系';
                }
            }

            //$this->redirect('User/Index/index',$msg);

            $this->success($msg, U('User/Index/index'));
        } else {
            $this->error('注册失败');
        }

    }

    public function activate()
    {
        header("Content-Type:text/html; charset=utf-8");

        $id = I('va', 0, 'intval');
        $code = I('vc', '', 'htmlspecialchars,trim');
        if (empty($code) || $id == 0) {
            exit('你的效验串不合法！<a href="' . C('cfg_weburl') . '">返回首页</a>');
        }
        $row = M('active')->where(array('id' => $id, 'expire' => array('gt', time())))->find();
        if ($code != $row['code']) {
            exit('激活码过期或错误！<a href="' . C('cfg_weburl') . '">返回首页</a>');
        }

        M('member')->where(array('id' => $row['userid']))->setField('status', '1'); //激活用户状态设置
        //M('active')->delete($id);//从激活表中删除
        M('active')->where(array('id' => $row['id']))->setField('expire', '0'); //激活用户状态设置
        // 清除会员缓存
        //DelCache($mid);
        $this->success('激活操作成功，请重新登录！', U('User/Index/index'));

    }


    public function logout()
    {

        $furl = htmlspecialchars($_SERVER['HTTP_REFERER']);

        if (empty($furl) || strpos($furl, 'register') || strpos($furl, 'login') || strpos($furl, 'activate') || strpos($furl, 'sendActivate')) {
            $furl = U(MODULE_NAME . '/Index/index');

        }

        del_cookie(array('name' => 'uid'));
        del_cookie(array('name' => 'email'));
        del_cookie(array('name' => 'nickname'));
        del_cookie(array('name' => 'logintime'));
        del_cookie(array('name' => 'loginip'));
        del_cookie(array('name' => 'status'));
        $this->success('安全退出', $furl);
    }


    //显示验证码
    public function get_verify()
    {
        $Verify = new \Think\Verify();
        $Verify->codeSet = '0123456789';
        $Verify->length = 3;
        $Verify->entry(1);
    }

    /*
上传图片
 */
    public function upload()
    {
        //3.2上传
        if (IS_POST) {
            $upload = new \Think\Upload();
            $upload->maxSize = 3145728;
            $upload->exts = array('jpg', 'gif', 'png', 'jpeg');
            $upload->savePath = 'image/';
            $info = $upload->upload();
            if (!$info) {
                $this->error($upload->getError());
                exit;
            } else {
                $db = M('attachment');
                foreach ($info as $file) {
                    //入库附件表格
                    $savepath = $file['savepath'];
                    $data['filepath'] = ltrim(C('ROOTPATH'), ".") . $savepath . $file['savename'];
                    $data['title'] = $file['name'];
                    $data['haslitpic'] = empty($file['haslitpic']) ? 0 : 1;
                    $filetype = 1;
                    //后缀
                    switch ($file['ext']) {
                        case 'gif':
                            $filetype = 1;
                            break;
                        case 'jpg':
                            $filetype = 1;
                            break;
                        case 'png':
                            $filetype = 1;
                            break;
                        case 'bmp':
                            $filetype = 1;
                            break;
                        case 'swf': //flash
                            $filetype = 2;
                            break;
                        case 'mp3': //音乐
                            $filetype = 3;
                            break;
                        case 'wav':
                            $filetype = 3;
                            break;
                        case 'rm': //电影
                            $filetype = 4;
                            break;

                        case 'doc': //
                            $filetype = 5;
                            break;
                        case 'docx': //
                            $filetype = 5;
                            break;
                        case 'xls': //
                            $filetype = 5;
                            break;
                        case 'ppt': //
                            $filetype = 5;
                            break;
                        case 'zip': //
                            $filetype = 6;
                            break;
                        case 'rar': //
                            $filetype = 6;
                            break;
                        case '7z': //
                            $filetype = 6;
                            break;

                        default: //其他
                            $filetype = 0;
                            break;
                    }
                    $data['filetype'] = $filetype;
                    $data['filesize'] = $file['size'];
                    $data['uploadtime'] = time();
                    $data['aid'] = $_SESSION['aid']; //管理员ID
                    $db->add($data);
                    //入库附件表结束
                    echo json_encode(array('status' => 1, 'path' => ltrim(C('ROOTPATH'), ".") . $file['savepath'] . $file['savename'], 'title' => $file['name'], 'size' => $file['size']));
                }
                exit;
            }
        } else {
            exit;
        }
    }
}